"use client"

import type React from "react"

import { useState, useRef, useCallback, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Textarea } from "@/components/ui/textarea"
import { ArrowLeft, Image, MapPin, Music, Video, Globe, Lock, Users, X } from "lucide-react"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { MusicPicker } from "@/components/resource-picker/music-picker"
import { MVPicker } from "@/components/resource-picker/mv-picker"
import { toast } from "@/components/ui/use-toast"
import { cn } from "@/lib/utils"
import { LocationPicker } from "@/components/resource-picker/location-picker"

interface MediaContent {
  type: "image" | "music" | "video"
  data: any
}

interface Location {
  name: string
  address: string
  distance: number
  city?: string
}

export default function CreatePostPage() {
  const [content, setContent] = useState("")
  const [showMediaOptions, setShowMediaOptions] = useState(false)
  const [visibility, setVisibility] = useState("public")
  const [location, setLocation] = useState<{ display: string; coords: string | null }>({ display: "", coords: null })
  const [isGettingLocation, setIsGettingLocation] = useState(false)
  const [isGettingDetailedLocation, setIsGettingDetailedLocation] = useState(false)
  const [mediaContent, setMediaContent] = useState<MediaContent | null>(null)
  const [showMusicPicker, setShowMusicPicker] = useState(false)
  const [showMVPicker, setShowMVPicker] = useState(false)
  const [showLocationPicker, setShowLocationPicker] = useState(false)
  const [selectedLocation, setSelectedLocation] = useState<Location | null>(null)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const router = useRouter()

  const getLocation = useCallback(() => {
    if (!navigator.geolocation) {
      toast({
        title: "错误",
        description: "您的浏览器不支持地理位置",
      })
      return
    }

    setIsGettingLocation(true)

    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords
        setLocation({ display: "正在获取详细地址...", coords: `${latitude},${longitude}` })
        setIsGettingLocation(false)
        setIsGettingDetailedLocation(true)
      },
      (error) => {
        let errorMessage
        switch (error.code) {
          case error.PERMISSION_DENIED:
            errorMessage = "用户拒绝了地理位置请求"
            break
          case error.POSITION_UNAVAILABLE:
            errorMessage = "位置信息不可用"
            break
          case error.TIMEOUT:
            errorMessage = "获取位置信息超时"
            break
          default:
            errorMessage = "发生未知错误"
        }
        toast({
          title: "获取位置失败",
          description: errorMessage,
        })
        setIsGettingLocation(false)
      },
      { timeout: 10000 }, // 10秒超时
    )
  }, [])

  useEffect(() => {
    if (isGettingDetailedLocation && location.coords) {
      // 这里应该调用后端API来获取详细地址
      // 为了演示，我们使用setTimeout模拟API调用
      const timer = setTimeout(() => {
        setLocation((prev) => ({ ...prev, display: "广东省深圳市南山区科技园" }))
        setIsGettingDetailedLocation(false)
      }, 2000)

      return () => clearTimeout(timer)
    }
  }, [isGettingDetailedLocation, location.coords])

  const handleSubmit = async () => {
    if (!content.trim()) {
      toast({
        title: "请输入内容",
        description: "内容不能为空",
      })
      return
    }

    try {
      // 创建一个FormData对象来处理文件上传
      const formData = new FormData()
      formData.append("content", content)
      formData.append("visibility", visibility)
      if (location.coords) formData.append("location", location.coords)

      if (mediaContent) {
        formData.append("mediaType", mediaContent.type)
        if (mediaContent.data.file) {
          formData.append("mediaFile", mediaContent.data.file)
        } else {
          formData.append("mediaId", mediaContent.data.id.toString())
        }
      }

      // 这里应该调用API来保存帖子，包括文件上传
      console.log("发布内容:", formData)

      // 模拟API调用
      await new Promise((resolve) => setTimeout(resolve, 1000))

      toast({
        title: "发布成功",
        description: "您的动态已经成功发布",
      })

      router.push("/community")
    } catch (error) {
      toast({
        title: "发布失败",
        description: "请稍后重试",
      })
    }
  }

  const handleImageSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (file) {
      // 处理图片上传
      const reader = new FileReader()
      reader.onloadend = () => {
        setMediaContent({
          type: "image",
          data: {
            url: reader.result,
            name: file.name,
          },
        })
      }
      reader.readAsDataURL(file)
    }
  }

  const handleMusicSelect = (song: any) => {
    setMediaContent({
      type: "music",
      data: {
        ...song,
        isExternal: !!song.file, // 使用file属性来判断是否为外部资源
      },
    })
    setShowMusicPicker(false)
  }

  const handleMVSelect = (mv: any) => {
    setMediaContent({
      type: "video",
      data: {
        ...mv,
        isExternal: !!mv.file, // 使用file属性来判断是否为外部资源
      },
    })
    setShowMVPicker(false)
  }

  const removeMedia = () => {
    setMediaContent(null)
  }

  const handleLocationSelect = (location: Location | null) => {
    setSelectedLocation(location)
    setShowLocationPicker(false)
  }

  return (
    <div className="min-h-screen bg-background">
      <div className="fixed top-0 left-0 right-0 bg-background border-b p-4 flex items-center justify-between z-10">
        <Button variant="ghost" size="icon" onClick={() => router.back()}>
          <ArrowLeft className="h-6 w-6" />
        </Button>
        <h1 className="text-lg font-semibold">发布动态</h1>
        <div className="w-10"></div> {/* 占位，保持标题居中 */}
      </div>

      <div className="pt-16 px-4 pb-20 max-w-2xl mx-auto">
        <Textarea
          placeholder="分享你的想法..."
          value={content}
          onChange={(e) => setContent(e.target.value)}
          className="w-full min-h-[200px] text-lg border-none resize-none focus-visible:ring-0"
          maxLength={1000}
          autoFocus
        />

        {/* 媒体内容预览 */}
        {mediaContent && (
          <div className="mt-4 relative">
            <div className="relative rounded-lg overflow-hidden bg-muted">
              {mediaContent.type === "image" && (
                <img
                  src={mediaContent.data.url || URL.createObjectURL(mediaContent.data.file)}
                  alt="预览图片"
                  className="w-full object-contain max-h-[400px]"
                />
              )}
              {mediaContent.type === "music" && (
                <div className="flex items-center space-x-4 p-4">
                  <img
                    src={mediaContent.data.cover || "/placeholder.svg"}
                    alt={mediaContent.data.title}
                    className="w-16 h-16 rounded"
                  />
                  <div>
                    <h4 className="font-medium">{mediaContent.data.title}</h4>
                    <p className="text-sm text-muted-foreground">{mediaContent.data.artist}</p>
                    {mediaContent.data.isExternal && <p className="text-xs text-muted-foreground mt-1">外部资源</p>}
                  </div>
                </div>
              )}
              {mediaContent.type === "video" && (
                <div className="aspect-video">
                  {mediaContent.data.isExternal ? (
                    <video
                      src={URL.createObjectURL(mediaContent.data.file)}
                      className="w-full h-full object-cover"
                      controls
                    />
                  ) : (
                    <img
                      src={mediaContent.data.cover || "/placeholder.svg"}
                      alt={mediaContent.data.title}
                      className="w-full h-full object-cover"
                    />
                  )}
                  <div className="absolute bottom-0 left-0 right-0 p-4 bg-gradient-to-t from-black/60">
                    <h4 className="text-white font-medium">{mediaContent.data.title}</h4>
                    <p className="text-white/80 text-sm">{mediaContent.data.artist}</p>
                    {mediaContent.data.isExternal && <p className="text-xs text-white/60 mt-1">外部资源</p>}
                  </div>
                </div>
              )}
              <Button variant="secondary" size="icon" className="absolute top-2 right-2" onClick={removeMedia}>
                <X className="h-4 w-4" />
              </Button>
            </div>
          </div>
        )}

        <div className="flex justify-between mt-4">
          <div className="flex space-x-2">
            <input type="file" accept="image/*" className="hidden" ref={fileInputRef} onChange={handleImageSelect} />
            <Button variant="ghost" size="icon" onClick={() => fileInputRef.current?.click()} disabled={!!mediaContent}>
              <Image className="h-5 w-5" />
            </Button>
            <Button variant="ghost" size="icon" onClick={() => setShowMVPicker(true)} disabled={!!mediaContent}>
              <Video className="h-5 w-5" />
            </Button>
            <Button variant="ghost" size="icon" onClick={() => setShowMusicPicker(true)} disabled={!!mediaContent}>
              <Music className="h-5 w-5" />
            </Button>
            <Button
              variant="ghost"
              size="icon"
              onClick={() => setShowLocationPicker(true)}
              className={cn(selectedLocation && "text-primary")}
            >
              <MapPin className="h-5 w-5" />
            </Button>
          </div>
          <div className="text-sm text-muted-foreground">{content.length}/1000</div>
        </div>

        {selectedLocation && (
          <div className="flex items-center gap-2 mt-4 text-[#00b578]">
            <MapPin className="h-5 w-5" />
            <span className="text-sm">
              {selectedLocation.city ? `${selectedLocation.city}·${selectedLocation.name}` : selectedLocation.name}
            </span>
          </div>
        )}

        {location.display && (
          <div className="mt-4 flex items-center justify-between bg-muted p-2 rounded">
            <span className="text-sm">{location.display}</span>
            <Button variant="ghost" size="sm" onClick={() => setLocation({ display: "", coords: null })}>
              <X className="h-4 w-4" />
            </Button>
          </div>
        )}

        <div className="mt-6 space-y-4">
          <div className="flex items-center space-x-2">
            <span className="text-sm font-medium">可见范围</span>
            <Select value={visibility} onValueChange={setVisibility}>
              <SelectTrigger className="w-[180px]">
                <SelectValue placeholder="选择可见范围" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="public">
                  <div className="flex items-center">
                    <Globe className="mr-2 h-4 w-4" />
                    <span>公开</span>
                  </div>
                </SelectItem>
                <SelectItem value="friends">
                  <div className="flex items-center">
                    <Users className="mr-2 h-4 w-4" />
                    <span>仅好友可见</span>
                  </div>
                </SelectItem>
                <SelectItem value="private">
                  <div className="flex items-center">
                    <Lock className="mr-2 h-4 w-4" />
                    <span>仅自己可见</span>
                  </div>
                </SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="mt-8">
          <Button onClick={handleSubmit} className="w-full">
            发表
          </Button>
        </div>
      </div>

      {/* 资源选择器 */}
      <MusicPicker open={showMusicPicker} onOpenChange={setShowMusicPicker} onSelect={handleMusicSelect} />
      <MVPicker open={showMVPicker} onOpenChange={setShowMVPicker} onSelect={handleMVSelect} />
      <LocationPicker
        open={showLocationPicker}
        onOpenChange={setShowLocationPicker}
        onSelect={handleLocationSelect}
        currentLocation={selectedLocation}
      />
    </div>
  )
}

